package com.tfjybj.itoo.exam.provider.until;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Sheet;
import org.jplus.hyberbin.excel.service.ExportExcelService;
import org.jplus.hyberbin.excel.utils.ExcelUtil;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

public class MutliExcelUtil<T> extends ExcelUtil<T>{

    Class<T> clazz;


    public MutliExcelUtil(Class<T> clazz) {
        super(clazz);
    }

    private static void setFileName(HttpServletResponse response, String name) throws UnsupportedEncodingException {
        // 设置导出默认文件名为当前时间：年月日时分秒

        String fileName="";
        if ("".equals(name.trim())){
            fileName = new SimpleDateFormat("yyyyMMddhhmmss").format(
                    new Date());
        }else{
            fileName = name;
        }
        // 设置response头信息
        response.reset();
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/vnd.ms-excel"); // 改成输出excel文件
        response.setHeader("Content-disposition", "attachment; filename="
                + new String(fileName.getBytes("gb2312"), "ISO8859-1" ) + ".xls");
    }

    /**
     * 无字典的导出Excel
     *
     * @param conditionMap
     * @param response
     * @throws Exception
     */
    public static <T> void exportExcel(Map<Serializable, Serializable> conditionMap, HttpServletResponse response) throws Exception {
        String sheetName = conditionMap.get("sheetName").toString();
        String[] columns = (String[]) conditionMap.get("columns");
        String title = conditionMap.get("title").toString();
        String name = conditionMap.get("name") == null?"":conditionMap.get("name").toString();
        try {
            if(name==null){
                name = "";
            }
            HSSFWorkbook workbook = new HSSFWorkbook();
            Sheet sheet = workbook.createSheet(sheetName);
            //List<T> dataList = (List<T>) conditionMap.get("dataList");
            ExportExcelService service = new ExportExcelService(conditionMap.get("dataList"), sheet, columns, title);
            service.doExport();
            //设置导出文件名
            setFileName(response,name);
            // 创建工作簿并发送到浏览器
            OutputStream out = response.getOutputStream();
            workbook.write(out);
            if (null != out) {
                out.close();
            }
        } catch (Exception e) {
            throw e;
        }
    }
}
